import 'package:dio/dio.dart';
import 'package:lib_http/http/net_code.dart';

/// 网络请求错误
class HttpError {
  /// 状态码
  late String code;

  /// 错误信息
  late String msg;

  HttpError(this.code, {this.msg = ""});

  /// 解析dio错误
  HttpError.dioError(DioException error) {
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
        // 网络连接超时
        code = NetCode.connectionTimeOut;
        break;
      case DioExceptionType.sendTimeout:
        // 发送数据超时
        code = NetCode.sendTimeout;
        break;
      case DioExceptionType.receiveTimeout:
        // 数据接收超时
        code = NetCode.sendTimeout;
        break;
      case DioExceptionType.badCertificate:
        // 证书验证有误
        code = NetCode.badCertificate;
        break;
      case DioExceptionType.badResponse:
        // 网络无响应
        code = NetCode.response;
        break;
      case DioExceptionType.cancel:
        // 网络无响应
        code = NetCode.cancel;
        break;
      case DioExceptionType.connectionError:
        // 网络发生异常
        code = NetCode.connectionError;
        break;
      case DioExceptionType.unknown:
        // 网络发生异常
        code = NetCode.unknown;
        break;
      default:
        code = "${error.hashCode}";
        break;
    }
    msg = error.message != null ? error.message! : "";
  }

  @override
  String toString() {
    return "{code: $code, msg: $msg}";
  }
}
